// 实现这个项目的构建任务
const sass = require('sass');
const loadGruntTasks = require('load-grunt-tasks');


let config = {};
try {
  config = require('./pages.config')
} catch {
  
}

module.exports = grunt => { 
  grunt.initConfig({
    clean: {
      temp: 'temp/**'
    },
    sass: {
      options: {
        sourceMap: true,
        implementation: sass
      },
      main: {
        files: {
          'temp/assets/styles/main.css': 'src/assets/styles/main.scss'
        }
      }
    },
    babel: {
      options: {
        sourceMap: true,
        presets: ['@babel/preset-env']
      },
      main: {
        files: {
          'temp/assets/scripts/main.js': 'src/assets/scripts/main.js'
        }
      }
    },
    swig: {
      options: {
        data: config,
      },
      main: {
        files: {
          'temp/index.html': 'src/index.html',
          'temp/about.html': 'src/about.html'
        }
      }
    },
    imagemin: {
      dist: {
        options: {
          optimizationLevel: 1,
        },
        files: [{
          expand: true,
          cwd: 'src/assets/images/',
          src: ['**'],
          // dest: 'temp/assets/images/'
          dest: 'dist/assets/images/'
        }, {
          expand: true,
          cwd: 'src/assets/fonts/',
          src: ['**'],
          // dest: 'temp/assets/fonts/'
          dest: 'dist/assets/fonts/'
        }]
      }
    },
    useref: {
      html: 'temp/*.html',
      temp: 'temp'
    },
    {
      options: {
        separator: ';',
        stripBanners: true
      },
      js: {
        src: [
          'temp/assets/script/*.js'
        ],
        dest: 'dist/assets/scripts'
      },
      css: {
        src: [
          'temp/assets/styles/*.css'
        ],
        dest: 'dist/assets/styles'
      }
    },
    cssmin: {
      css: {
        files: {
          'dist/assets/styles/main.css': 'temp/assets/styles/main.css'
        }
      }
    },
    uglify: {
      js: {
        expand: true,
        //相对路径
        cwd: 'temp/assets/script',
        src: '*.js',
        dest: 'dist/assets/script/'
      }
    },
    htmlmin: {
      dist: {
        options: {
          removeComments: true,
          collapseWhitespace: true
        },
        files: {
          'dist/index.html': 'temp/index.html',
          'dist/about.html': 'temp/about.html'
        }
      }
    },
    watch: {
      js: {
        files: ['src/assets/scripts/*.js'],
        tasks: ['babel']
      },
      css: {
        files: ['src/assets/styles/*.scss'],
        tasks: ['sass']
      }
    }
  });
  loadGruntTasks(grunt);
  grunt.registerTask('compile', ['sass', 'babel', 'swig']);
  grunt.registerTask('develop', []);
  grunt.registerTask('build', ['clean', 'compile', 'useref', 'concat', 'cssmin', 'uglify', 'htmlmin', 'imagemin']);
}